﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
namespace ReconCaracteres_Backpropagation
{
    public partial class TrainningForm : Form
    {
        public Sample selectedSample;
        public BackPropagationNetwork b;
        public TrainningForm()
        {
            InitializeComponent();

            this.pictureBoxSign.Size = new System.Drawing.Size(100, 100);
           // this.IDlabel.Text = "";

        }

        private void TrainningForm_Load(object sender, EventArgs e)
        {

        }

        private void loadSamplebutton_Click(object sender, EventArgs e)
        {

            

            openFileDialog.ShowDialog();
            

            selectedSample = new Sample(openFileDialog.FileName);



        //    this.IDlabel.Text = selectedSample.ID;
            this.pictureBoxSign.Image = selectedSample.getBitmap(); 
            pictureBoxSign.SizeMode = PictureBoxSizeMode.StretchImage;
        }

        private void conjuntoMuestraslistBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((Sample)((ListBox)(sender)).SelectedItem)!=null)
            {

                this.pictureBoxSign.Image = ((Sample)((ListBox)(sender)).SelectedItem).getBitmap();//selectedSample.getBitmap();
                pictureBoxSign.SizeMode = PictureBoxSizeMode.StretchImage;
            }
            
        }

       /* private void AgregarButton_Click(object sender, EventArgs e)
        {
                       
            if (this.categoriesSetcomboBox.SelectedItem == null  || this.selectedSample==null)
            {
                MessageBox.Show("Seleccione una categoría/muestra");
                return;
            }
            selectedSample.category = this.categoriesSetcomboBox.SelectedItem.ToString();
           // this.selectedSample.setExpectedVector(this.categoriesSetcomboBox.SelectedIndex, this.categoriesSetcomboBox.Items.Count);
            this.SamplesSetlistBox.Items.Add(this.selectedSample);
    
        }*/

        private void initializeWeightsButton_Click(object sender, EventArgs e)
        {
            saveFileDialog.Title = "Guardar pesos aleatorios";
            saveFileDialog.ShowDialog();


            if (saveFileDialog.FileName != "")
            {

                MyFile file = new MyFile(saveFileDialog.FileName);
                file.writeWeights(Int32.Parse(this.inputNeuronsTextBox.Text), Int32.Parse(this.hiddenNeuronsTextBox.Text), Int32.Parse(this.outputNeuronsTextBox.Text)+1);
                file.close();
                weightsTextBox.Text = Path.GetFileName(saveFileDialog.FileName);
            }

        }

        private void trainButton_Click(object sender, EventArgs e)
        {
            //this.trainButton.Enabled = false;

            //Cursors.WaitCursor reloj= new 
            this.Cursor = Cursors.WaitCursor;
            //this.Cursor=
  

 

            Double alpha = .8;
            int inputLayerNeuronsAmount = Int32.Parse(this.inputNeuronsTextBox.Text);
            int hiddenLayerNeuronsAmount = Int32.Parse(this.hiddenNeuronsTextBox.Text);
            int outputLayerNeuronsAmount = Int32.Parse(this.outputNeuronsTextBox.Text)+1;
            b = new BackPropagationNetwork(alpha, inputLayerNeuronsAmount, hiddenLayerNeuronsAmount, outputLayerNeuronsAmount);
            //b.inputLayer.loadAllInputWeights("Weights.txt");
            //b.hiddenLayer.loadAllOutputWeights("Weights.txt");
            b.inputLayer.loadAllInputWeights(this.weightsTextBox.Text.Trim());
            b.hiddenLayer.loadAllOutputWeights(this.weightsTextBox.Text.Trim());

            int iterationsCounter = 0;

      
 
                while (!b.stopTrainningFlag)
                {
                    //Double errors[]  = new Double[this.SamplesSetlistBox.Items.Coun];
                    Double averageError=0;
                    b.stopTrainningFlag = true;
                    for (int i = 0; i < this.SamplesSetlistBox.Items.Count; i++)
                    {
                            Sample sample = ((Sample)this.SamplesSetlistBox.Items[i]);
                            Double[] input = sample.getInputVector();
                            Double[] d = sample.getVectorD(sample.expectedVector);
                            averageError += b.propagateInput(input, d);
                            
                    }
                    averageError = averageError / SamplesSetlistBox.Items.Count;
                    if (iterationsCounter%10==0)
                    {
                        chart1.Series["Error"].Points.AddY(averageError);
                    }
                iterationsCounter++;
            }


            MessageBox.Show("Entrenamiento terminado en "+iterationsCounter+" iteraciones");
            this.saveWeightsbutton.Enabled = true;

            this.Cursor = Cursors.Arrow;


        }

        private void classifyButton_Click(object sender, EventArgs e)
        {
            openFileDialog.ShowDialog();

            // String imageDir = openFileDialog.FileName;
            Sample selectedSampleToClassify = new Sample(openFileDialog.FileName);
            Double[] output=b.clasifyInput(selectedSampleToClassify.getInputVector());
            this.pictureBoxSign.Image = selectedSampleToClassify.getBitmap(); 
            foreach (Double i in output)
            {
                Console.Write("["+i+"]");
            }
            Console.Write("\n");

        }

        private void SamplesSetGroupBox_Enter(object sender, EventArgs e)
        {

        }

        private void SampleGroupBox_Enter(object sender, EventArgs e)
        {

        }

        private void loadSamplesButton_Click(object sender, EventArgs e)
        {

            openFileDialog.ShowDialog();


            if (openFileDialog.FileName!=null)
            {
                this.Samples0SetlistBox.Items.Clear();
                this.Samples1SetlistBox.Items.Clear();
                this.Samples2SetlistBox.Items.Clear();
                this.Samples3SetlistBox.Items.Clear();
                this.Samples4SetlistBox.Items.Clear();
                this.Samples5SetlistBox.Items.Clear();
                this.Samples6SetlistBox.Items.Clear();
                this.Samples7SetlistBox.Items.Clear();
                this.Samples8SetlistBox.Items.Clear();
                this.Samples9SetlistBox.Items.Clear();
                this.SamplesSetlistBox.Items.Clear();
                MyReadFile mrf = new MyReadFile(openFileDialog.FileName);
                Sample sampleRead;
                while ((sampleRead = mrf.read()) != null)
                {
                    sampleRead.setExpectedVector(10);
                    this.SamplesSetlistBox.Items.Add(sampleRead);
                    switch (sampleRead.categoryIndex)
                    {
                        case 0:
                            this.Samples0SetlistBox.Items.Add(sampleRead);
                            break;
                        case 1:
                            this.Samples1SetlistBox.Items.Add(sampleRead);
                            break;
                        case 2:
                            this.Samples2SetlistBox.Items.Add(sampleRead);
                            break;
                        case 3:
                            this.Samples3SetlistBox.Items.Add(sampleRead);
                            break;
                        case 4:
                            this.Samples4SetlistBox.Items.Add(sampleRead);
                            break;
                        case 5:
                            this.Samples5SetlistBox.Items.Add(sampleRead);
                            break;
                        case 6:
                            this.Samples6SetlistBox.Items.Add(sampleRead);
                            break;
                        case 7:
                            this.Samples7SetlistBox.Items.Add(sampleRead);
                            break;
                        case 8:
                            this.Samples8SetlistBox.Items.Add(sampleRead);
                            break;
                        case 9:
                            this.Samples9SetlistBox.Items.Add(sampleRead);
                            break;
                        default:
                            MessageBox.Show("Categoría no identificada");
                            break;

                    }

                }
                samplesAmountlabel1.Text = "Entrenar las " + this.SamplesSetlistBox.Items.Count + " muestras";
                trainButton.Enabled = true;
            }
           /* mrf.read();
            mrf.read();
            mrf.read();*/
        }

        private void pictureBoxSign_Click(object sender, EventArgs e)
        {

        }

        private void saveWeightsbutton_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "Guardar archivo de pesos nuevos";
            saveFileDialog.ShowDialog();
            if (saveFileDialog.FileName!=null)
            {
                MyFile f = new MyFile(saveFileDialog.FileName);
                f.writeWeights(this.b);
                f.close();
            }
        }
    }
}
